package com.ideas.impl.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author lijian.wu
 * @Date 2024/3/18 11:12
 * 多个线程交叉执行
 */
public class CrossExec {

  static class Task implements Runnable{
      private static int num = 0;
      private int index;
      private static final ReentrantLock lock = new ReentrantLock();
      private static final Condition condition = lock.newCondition();

      public Task(int index) {
          this.index = index;
      }

      @Override
      public void run() {
            while (num < 100){
                lock.lock();
                try {
                    if (num % 3 == index){
                        System.out.println(Thread.currentThread().getName() + " : " + num);
                        num++;
                        condition.signalAll();
                    }else {
                        condition.await();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
      }
  }

  public static void main(String[] args) throws InterruptedException {
      new Thread(new Task(0)).start();
      new Thread(new Task(1)).start();
      new Thread(new Task(2)).start();
  }
}
